package top.rainbowecho.gateway.security.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.UserIdSource;
import top.rainbowecho.gateway.mapper.UserConnectionMapper;
import top.rainbowecho.model.field.UserConnectionField;
import top.rainbowecho.model.percona.UserConnection;

/**
 * @author rainbow
 * @since 2019/12/18 20:36
 */
public class AuthenticationIdUserIdSource implements UserIdSource {
    private UserConnectionMapper userConnectionMapper;

    public void setUserConnectionMapper(UserConnectionMapper userConnectionMapper) {
        this.userConnectionMapper = userConnectionMapper;
    }

    @Override
    public String getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
        }

        QueryWrapper<UserConnection> queryWrapper = new QueryWrapper<UserConnection>().eq(UserConnectionField.DISPLAY_NAME, authentication.getName());
        UserConnection userConnection = userConnectionMapper.selectOne(queryWrapper);
        return userConnection.getUserId();
    }
}
